package org.teremail.delivery;

import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import org.teremail.test.Assertion;

public class EasyMockUtils {

    public static <E> E argAssert(Assertion<E> assertion) {
        EasyMock.reportMatcher(new ArgumentMatcher(assertion));
        return null;
    }
    
    @SuppressWarnings("unchecked")
    public static class ArgumentMatcher implements IArgumentMatcher {

        private Assertion assertion;
        private Throwable assertionError;

        public ArgumentMatcher(Assertion assertion) {
            this.assertion = assertion;
        }

        public void appendTo(StringBuffer buffer) {
            buffer.append("argumentAssertion(exception ")
                .append(assertionError)
                .append(")");
        }

        public boolean matches(Object actual) {
            try {
                assertion.check(actual);
                return true;
            } catch (Throwable e) {
                assertionError = e;
                return false;
            }
        }
        
    }
}
